/**
 * This file is part of 1genia trampoline
 * Copyright (C) 2007 1genia (contact@1genia.com)
 *
 * This library is free software; you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as
 * published by the Free Software Foundation; version 3 of the License. 
 *
 * This library is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Library General Public License for more details. 
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; see the file COPYING.TXT.  If not,
 * write to the Free Software Foundation, Inc., 51 Franklin Street,
 * Fifth Floor, Boston, MA 02110-1301, USA. 
 **/
package com.genia.toolbox.persistence.memory.criteria.order;

import java.util.Comparator;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.genia.toolbox.persistence.basis.criteria.BasicCriteriaResult;
import com.genia.toolbox.persistence.criteria.order.Order;

/**
 * Comparator to sort queries.
 */
public class OrderComparator
    implements Comparator<List<BasicCriteriaResult<?>>>
{

  /**
   * the logging object.
   */
  private static final Logger LOGGER = LoggerFactory.getLogger(OrderComparator.class);

  /**
   * the <code>Order</code>s of this query.
   */
  private final transient List<? extends Order> orders;



  /**
   * Constructor.
   * 
   * @param orders
   *          the <code>Order</code>s of this query
   */
  public OrderComparator(final List<? extends Order> orders)
  {
    this.orders = orders;
  }



  /**
   * Compares its two arguments for order. Returns a negative integer, zero, or
   * a positive integer as the first argument is less than, equal to, or greater
   * than the second.
   * 
   * @param line1
   *          the first line of result
   * @param line2
   *          the second line of result
   * @return a negative integer, zero, or a positive integer as the first
   *         argument is less than, equal to, or greater than the second.
   * @see java.util.Comparator#compare(Object, Object)
   */
  public int compare(final List<BasicCriteriaResult<?>> line1, final List<BasicCriteriaResult<?>> line2)
  {
    for (final Order order : orders) {
      int res = 0;
      try {
        res = ((MemoryOrder) order).compare(line1, line2);
      }
      catch (final Exception e) {
        // Unable to let those exceptions go through...
        LOGGER.error(e.getMessage(), e);
      }
      if (res != 0) {
        return res;
      }
    }
    return 0;
  }

}
